package com.blogspot.security.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;

import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.blogspot.security.dao.UserDao;
import com.blogspot.security.domain.ApplicationUser;
import com.blogspot.security.service.impl.UserDetailsServiceImpl;


@Repository
public class UserDaoImpl implements UserDao {
	private Logger logger = LoggerFactory.getLogger(UserDaoImpl.class);
	
    @PersistenceContext
    EntityManager em;
    
    @Autowired
    protected HibernateTemplate template;

//    @Autowired
//    public void setSessionFactory(SessionFactory sessionFactory) {
//        template = new HibernateTemplate(sessionFactory);
//    }
    
    //由userName撈出使用者詳細資料
    @SuppressWarnings("unchecked")
	public ApplicationUser getUser(String userName) {
    	logger.error("Allan Sung getUser Enter");
    	try {
        	Object [] params = new Object [] {userName};
        	List<ApplicationUser> list = template.find("select u from ApplicationUser u where u.userName = ?", userName);
        	logger.error("Allan Sung getUser : " + list.size());
        	logger.error("Allan Sung getUser : " + list.get(0).getUserName());
        	return list == null ? null : list.get(0);
    	} catch (Exception e) {
    		e.printStackTrace();
    		logger.error("Allan Error : " + e.getMessage());
    	}
//        String queryString = "select u from AppUser u where u.userName = :userName";
//        TypedQuery<ApplicationUser> query = em.createQuery(queryString, ApplicationUser.class);
//        query.setParameter("userName", userName);
//        return query.getResultList().size() == 0 ? null : (AppUser)query.getResultList().get(0);
		return null;
    }
    
    //使用者總數
    public long getUserCount() {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Long> cq = builder.createQuery(Long.class);
        cq.select(builder.count(cq.from(ApplicationUser.class)));
        em.createQuery(cq);
        Long count = em.createQuery(cq).getSingleResult();
        return count;
    }
    
    public void updateUser(ApplicationUser user) {
        em.merge(user);
    }
}
